Android Java发送JSON POST请求,请求体为空。

huangapple go评论78阅读模式
英文:

Android java sending a JSON post request, body is empty

问题

private BroadcastReceiver onNotice = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        String packageName = intent.getStringExtra("package");
        String titleData = intent.getStringExtra("title");
        String textData = intent.getStringExtra("text");
        TableRow tr = new TableRow(getApplicationContext());
        tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
        TextView textview = new TextView(getApplicationContext());
        textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1.0f));
        textview.setTextSize(20);
        textview.setTextColor(Color.parseColor("#0B0719"));
        textview.setText(Html.fromHtml(packageName + "<br><b>" + titleData + " :</b>" + textData));
        tr.addView(textview);
        tab.addView(tr);

        try {
            URL url = new URL("https://[hidden].herokuapp.com/api");
            try {
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("POST");
                con.setRequestProperty("Content-Type", "application/json; utf-8");
                con.setRequestProperty("Accept", "application/json");
                con.setRequestProperty("token", "secret");
                con.setDoOutput(true);
                JSONObject jObjectData = new JSONObject();
                
                try {
                    jObjectData.put("package", packageName);
                    jObjectData.put("titleData", titleData);
                    jObjectData.put("textData", textData);
                } catch (JSONException ex) {
                    System.out.println(ex);
                }

                System.out.println(jObjectData);
                byte[] outputInBytes = jObjectData.toString().getBytes("UTF-8");
                OutputStream os = con.getOutputStream();
                os.write(outputInBytes);
                os.close();

                try (BufferedReader br = new BufferedReader(
                        new InputStreamReader(con.getInputStream(), "utf-8"))) {
                    StringBuilder response = new StringBuilder();
                    String responseLine = null;
                    while ((responseLine = br.readLine()) != null) {
                        response.append(responseLine.trim());
                    }
                    System.out.println(response.toString());
                }
            } catch (IOException ex) {
                System.out.println(ex);
            }
        } catch (MalformedURLException ex) {
            System.out.println(ex);
        }
    }
};

我知道代码中有些地方看起来比较混乱,这是因为我对Java和Android还很陌生,我只是想让这个简单的脚本能够工作。JSON对象是 jObjectData,它将通知转发给API,问题是每当我发送请求时,请求的主体在我的Node.js Express后端中无法显示出来。请求的主体显示为空对象 {},我完全不知道如何解决这个问题。

英文:

I am trying to send a simple request using Java for Android. I have implemented a script and everything seems to be working fine the request is being sent but the most important part the JSON object just doesnt show up on the backend, the body of the request is completely empty.

private BroadcastReceiver onNotice = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String packageName = intent.getStringExtra(&quot;package&quot;);
String titleData = intent.getStringExtra(&quot;title&quot;);
String textData = intent.getStringExtra(&quot;text&quot;);
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor(&quot;#0B0719&quot;));
textview.setText(Html.fromHtml(packageName + &quot;&lt;br&gt;&lt;b&gt;&quot; + titleData + &quot; : &lt;/b&gt;&quot; + textData));
tr.addView(textview);
tab.addView(tr);
try {
URL url = new URL(&quot;https://[hidden].herokuapp.com/api&quot;);
try {
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(&quot;POST&quot;);
con.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json; utf-8&quot;);
con.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;);
con.setRequestProperty(&quot;token&quot;, &quot;secret&quot;);
con.setDoOutput(true);
JSONObject jObjectData = new JSONObject();
try {
jObjectData.put(&quot;package&quot;, packageName);
jObjectData.put(&quot;titleData&quot;, titleData);
jObjectData.put(&quot;textData&quot;, textData);
}catch(JSONException ex) {
System.out.println(ex);
}
System.out.println(jObjectData);
byte[] outputInBytes = jObjectData.toString().getBytes(&quot;UTF-8&quot;);
OutputStream os = con.getOutputStream();
os.write( outputInBytes );
os.close();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), &quot;utf-8&quot;))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println(response.toString());
}
}catch (IOException ex){
System.out.println(ex);
}
} catch (MalformedURLException ex) {
System.out.println(ex);
}
}
};

I know some things are really messy its because i am very new to java and android, i just need to make this simple script work. The json object is jObjectData which forwards a notification to api, the problem is that whenever i send the request its body wont show up on my Node.js Express backend. The body shows up as {}, i am completely stuck how can i fix this?

答案1

得分: -1

由于某种原因,utf-8 导致了这个问题。
所以,代替

con.setRequestProperty("Content-Type", "application/json; utf-8");

我写了

con.setRequestProperty("Content-Type", "application/json");

现在它正常工作了,我不知道为什么会发生这种情况,也许在编码方面有一些交叉配置,导致我的服务器无法识别请求体。

英文:

For some reason the utf-8 causes this issue.
So instead of

con.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json; utf-8&quot;);

I wrote

con.setRequestProperty(&quot;Content-Type&quot;, &quot;application/json&quot;);

and now it works, i have no idea why this is happening, maybe there's some cross configuration about the encoding that caused my server to not recognize the body.

huangapple
  • 本文由 发表于 2020年8月15日 00:37:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/63416760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定