1

我正在尝试创建对以下 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 中打印它后,我收到以下回复说主机名无效。我在代码中输入的主机名有问题吗?请帮助,因为我是使用休息风格 api 的新手

4

1 回答 1

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;
}
于 2012-07-03T05:04:59.943 回答