gpt4 book ai didi

java - 在Android中发出POST请求

转载 作者:行者123 更新时间:2023-12-01 13:31:33 24 4
gpt4 key购买 nike

我正在尝试向我的POST应用中的服务器发出Android请求,但这没有发生。下面是代码-

try{

View p = (View) v.getRootView();

EditText usernamefield = (EditText)p.findViewById(R.id.username);
String username = usernamefield.getText().toString();
EditText passwordfield = (EditText)p.findViewById(R.id.pass);
String password = passwordfield.getText().toString();

String apiKey = "ac96d760cb3c33a1ee988750b0b2fd12";
String secret = "cd9118e8d1d32d003e0ed54a202c2bf8";

Log.i(TAG,password);

String authToken = computeMD5hash(username.toLowerCase()).toString()+computeMD5hash(password).toString();
String authSig = computeMD5hash("api_key"+apiKey+"authToken"+authToken+"method"+"auth.getMobileSession"+"username"+username+secret).toString();

Log.i(TAG,authToken);

HttpClient client = new DefaultHttpClient();
Log.i(TAG,"after client1");
HttpPost post = new HttpPost("http://ws.audioscrobbler.com/2.0/");
Log.i(TAG,"after client2");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i(TAG,post.getURI().toString()); //logs the URL
HttpResponse response = client.execute(post);

int status = response.getStatusLine().getStatusCode();
Log.i(TAG,"Status code is"+status);

Log.i(TAG,"after post");

InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,"UTF-8"));
if(response.getStatusLine().getStatusCode()!= org.apache.commons.httpclient.HttpStatus.SC_OK)
{
Log.i(TAG,"bad http response");
Toast.makeText(getApplicationContext(),"bad httpcode",Toast.LENGTH_LONG).show();
throw new Exception(response.getStatusLine().getReasonPhrase());
}
StringBuilder sb = new StringBuilder();
String s;
while(true)
{
s = buf.readLine();
if(s==null || s.length()==0)
break;
sb.append(s);

}
buf.close();
ips.close();
System.out.print(sb.toString());
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
catch(NoSuchAlgorithmException e)
{

}
catch(Exception e){

}


该代码一直执行到 Log.i(TAG,post.getURI().toString())日志语句为止。它将打印出生成的URL- http://ws.audioscrobbler.com/2.0/。没有附加参数(很奇怪)。

我不知道使用NameValuePairs向URL添加参数的实现有什么问题。

最佳答案

我确实有一种简单的方法将数据发布到服务器。请使用它,让我知道这是否对您有用:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("method", "auth.getMobileSession"));
nameValuePairs.add(new BasicNameValuePair("api_key", apiKey));
nameValuePairs.add(new BasicNameValuePair("api_sig", authSig));
nameValuePairs.add(new BasicNameValuePair("format", "json"));
nameValuePairs.add(new BasicNameValuePair("authToken", authToken));
nameValuePairs.add(new BasicNameValuePair("username", username));
//call to method
JSONObject obj = makeHttpRequest(nameValuePairs, "http://ws.audioscrobbler.com/2.0/", "POST");




public static JSONObject makeHttpRequest(List<NameValuePair> params, String url, String method) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
url = url.trim();
Log.e("FETCHING_DATA_FROM",""+url.toString());
HttpPost httpPost = new HttpPost(url);

HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);


httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET

if(params!=null){
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}

HttpGet httpGet = new HttpGet(url);
Log.e("FETCHING_DATA_FROM",""+url.toString());

HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 600000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 600000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();

} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}

关于java - 在Android中发出POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21535257/

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