gpt4 book ai didi

android - 如何通过多部分实体方法将值从应用程序传递到 api 端?

转载 作者:行者123 更新时间:2023-11-30 01:27:48 27 4
gpt4 key购买 nike

我想将值从应用程序端传递到 api。在此 api 调用中传递图像、名字、电子邮件、电话和位置。在 Debug模式下,检查值不会被传递。

代码下方

 File file = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
httpPost.addHeader("X-COMPANY", currentcity);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (imagepath != null) {
file = new File(imagepath);
entity.addPart("pic", new FileBody(file));
}
entity.addPart("firstname", new StringBody(firstName, ContentType.TEXT_PLAIN));
entity.addPart("email", new StringBody(email, ContentType.TEXT_PLAIN));
entity.addPart("telephone", new StringBody(phonenumber, ContentType.TEXT_PLAIN));
entity.addPart("location", new StringBody(locaity, ContentType.TEXT_PLAIN));
httpPost.setEntity(entity);
Log.d("URL Request: ", url.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);

最佳答案

我认为你没有正确传递标题。使用下面的代码-

HttpURLConnection httpcon = (HttpURLConnection) ((new URL(strUrl).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type-", "multipart/form-data");
httpcon.setRequestMethod("POST");

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (imagepath != null) {
file = new File(imagepath);
entity.addPart("pic", new FileBody(file));
}
entity.addPart("firstname", new StringBody(firstName, ContentType.TEXT_PLAIN));
entity.addPart("email", new StringBody(email, ContentType.TEXT_PLAIN));
entity.addPart("telephone", new StringBody(phonenumber, ContentType.TEXT_PLAIN));
entity.addPart("location", new StringBody(locaity, ContentType.TEXT_PLAIN));

httpcon.addRequestProperty(entity.getContentType().getName(), entity.getContentType().getValue());

httpcon.setUseCaches(false);
httpcon.setDoInput(true);
httpcon.setDoOutput(true);
httpcon.connect();

OutputStream os = httpcon.getOutputStream();
entity.writeTo(httpcon.getOutputStream());
os.close();
httpcon.connect();

int responseCode = httpcon.getResponseCode();

if(responseCode == 200)
{
InputStream inputStream = new BufferedInputStream(httpcon.getInputStream());
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);

BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);

StringBuilder stringBuilder = new StringBuilder();

String bufferedStrChunk = null;

while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}

return stringBuilder.toString();

}

关于android - 如何通过多部分实体方法将值从应用程序传递到 api 端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36197132/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com