Android URLConnection失败所以我试图发布数据到服务器,我得到了400代码。我知道这意味着它是一个糟糕的请求,并且是由于我认为的格式不正确。 所以这就是我被告知要形成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();
}
}
}
任何帮助将不胜感激。
使用凌空网络请求 –
老实说,我只是想东西了这里,所以我可以学到 – MNM