所以我试图将数据发布到服务器,然后我得到一个400代码。我知道这意味着它是一个糟糕的请求,而且由于我认为这是一个错误的json。 所以这就是我被告知要形成json的方式
curl -i -u admin:admin -H "Content-Type: application/json" -X POST –d '{"customer_id":1, "device_id":"1234", "notification_id":"NOTIFICATIONID123456", "operating_system_type":"IOS"}' localhost:8090/api/1.0/notificationInformation
所以现在我不知道服务器是问题还是我的代码是问题。我以前遇到过android HttpUrlConnection的问题。
所以这是我的http处理程序类:
public class MyHttpPost extends AsyncTask<String, Void, String> {
private String username;
private String password;
private String json = "{\"customer_id\": \"000234\" , \"device_id\":\"1234443\", \"notification_id\":\"fLqDFPgBHcs:APA91bHHIB7kyTRqR18pK78k81AbV211jdhIyNlWK-CmejFKIK6FZJgx4R-7uzyfYLTqi_jhqclks07nkkQFnORXOU28wJ5qC3GIIY_WPaNxKCxIUTltMaWihPGcvaeOgyW7669M3K1n\", \"operating_system_type\":\"Android\"}";
///api/1.0/notificationInformation
public MyHttpPost(){}
public MyHttpPost(String username, String password)
{
this.username = username;
this.password = password;
}
@Override
protected String doInBackground(String... params) {
String url = params[0];
postHttp(url);
return null;
}
public void postHttp(String myUrl)
{
Log.d("Button ", "Pushed");
try {
URL url = new URL(myUrl);
if (username!=null)
{
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password.toCharArray());
}
});
}
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Allow Outputs (sending)
connection.setDoOutput(true);
Log.d("Allows input: ", Boolean.toString(connection.getDoInput()));
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
DataOutputStream printout = new DataOutputStream(connection.getOutputStream());
//printout.write(json.toString().getBytes("UTF8"));
printout.write(json.getBytes("UTF8"));
printout.flush();
printout.close();
int statuscode = connection.getResponseCode();
Log.d("Response code: " , Integer.toString(statuscode));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
对此有任何帮助将不胜感激。
答案 0 :(得分:1)
试试这个
URL url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
JSONObject postDataParams = new JSONObject();
try {
postDataParams.put("username","myname");
postDataParams.put("password", "mypwd");
} catch (JSONException e) {
e.printStackTrace();
}
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(postDataParams);
out.close();
int responseCode=conn.getResponseCode();