我正在尝试为以下api创建一个帖子请求:
consumer.api.mobdev.machies.com
为了做到这一点,我写了以下代码:
HttpPost httpPost = new HttpPost("http://consumer.api.mobdev.machies.com/v3/logins");
try {
// Add user name and password
EditText uname = (EditText)findViewById(R.id.username);
String username = uname.getText().toString();
EditText pword = (EditText)findViewById(R.id.password);
String password = pword.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("grant_type","password"));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
httpPost.setHeader("Host","http://consumer.api.mobdev.machies.com");
httpPost.setHeader("Content-Type","application/xml");
httpPost.setHeader("Accept-Language","en-US");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
Log.w("Post", "Execute HTTP Post Request");
HttpResponse response = httpclient.execute(httpPost);
String str = inputStreamToString(response.getEntity().getContent()).toString();
str指的是我得到的回应。在logcats中打印它时,我得到以下响应,说明无效的主机名。我在代码中添加的主机名是否有问题?请帮忙,因为我不熟悉使用rest style apis
答案 0 :(得分:0)
可能在这里使用HttpClient它可以帮助你
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(strUrl);
if (mHeader != null) {
for (Header header : mHeader) {
httpPost.addHeader(header);
}
}
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (nameValuePair != null) {
ContentBody cb;
for(NameValuePair value: nameValuePair){
cb = new StringBody(value.getValue(),"", null);
entity.addPart(value.getName(), cb);
}
}
if(filepath != null && filepath.length() > 0){
File f = new File(filepath);
entity.addPart("uploadedfile", new FileBody(f));
}
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
response = EntityUtils.toString(httpResponse.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
//Display();
} catch (IOException e) {
e.printStackTrace();
//Display();
}
if (mIsProgress)
progress.dismiss();
return response;
}