gpt4 book ai didi

android - okhttp替代容器

转载 作者:行者123 更新时间:2023-11-29 15:09:35 24 4
gpt4 key购买 nike

好吧,我对 okhttp 的理解有问题。我只需要将图像上传到服务器即可。

enter image description here

这张图片是我的 android studio 的截图,看来我不能 import org.apache.http.NameValuePair; 那什么是替代容器呢?

正如您注意到的,.open(url) 也是红色的,表示 cannot resolve java.net.url

这是我的完整代码:

public JSONObject getJSONFromUrl(String str_url, List<NameValuePair> params) {
String reply_str = null;
BufferedReader reader = null;
final ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("image",image_str));
nameValuePairs.add(new BasicNameValuePair("caption",caption));
nameValuePairs.add(new BasicNameValuePair("categorie",categorie));
try {
URL url = new URL(str_url);
OkHttpClient client = new OkHttpClient();
HttpURLConnection con = client.open(url);
con.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream());
writer.write(getEncodedParams(params));
writer.flush();
StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reply_str = sb.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

// try parse the string to a JSON object. There are better ways to parse data.
JSONObject jObj;
try {
jObj = new JSONObject(reply_str);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}

//in this case it's NameValuePair, but you can use any container
public String getEncodedParams(List<NameValuePair> params) {
StringBuilder sb = new StringBuilder();
for (NameValuePair nvp : params) {
String key = nvp.getName();
String param_value = nvp.getValue();
String value = null;
try {
value = URLEncoder.encode(param_value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}

最佳答案

您可以使用 Pair 而不是 BasicNameValuePair

getKey() 的等价物是pair.first。 getValue() 的一个将是 pair.second

关于android - okhttp替代容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33064171/

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