gpt4 book ai didi

java - Android 开发中如何在没有 BasicNameValuePair 的情况下将数据发送到 PHP 脚本

转载 作者:行者123 更新时间:2023-12-01 18:04:29 24 4
gpt4 key购买 nike

我正在使用一些在线教程学习 Android。除了这个之外,我所有的 Java 类(class)都很好。

@Override
protected Void doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("email", user.userEmail));
dataToSend.add(new BasicNameValuePair("fname", user.firstName));
dataToSend.add(new BasicNameValuePair("lname", user.lastName));
dataToSend.add(new BasicNameValuePair("password", user.password));

HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "register.php");

try{
post.setEntity(new UrlEncodedFormaEntity(dataToSend));
client.execute(post);
}catch (Exception e){
e.printStackTrace();

}
return null;
}

这是所有导入

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;

import java.util.ArrayList;

Screenshot of the error parts

我已经搜索了与此相关的其他问题,但我真的想要专门针对我的情况的答案。请指教。

最佳答案

创建一个新类。即 RestClient.java

public class RestClient {


private static String SERVICE_URL;

private ArrayList<NameValuePair> params;
private ArrayList <NameValuePair> headers;

private int responseCode;
private String message;

private String response;

public String getResponse() {
return response;
}

public String getErrorMessage() {
return message;
}

public int getResponseCode() {
return responseCode;
}

public RestClient(String serviceMethod)
{
SERVICE_URL = serviceMethod;
//this.serviceMethod = serviceMethod;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}

public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}

public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}

public String Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}

//SERVICE_URL +=serviceMethod;
HttpGet request = new HttpGet(SERVICE_URL + combinedParams);

//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}

executeRequest(request, SERVICE_URL);
break;
}
case POST:
{
//SERVICE_URL +=serviceMethod;
HttpPost request = new HttpPost(SERVICE_URL);

//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}

if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}

executeRequest(request, SERVICE_URL);
break;
}
}
return response;
}

private String executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();

HttpResponse httpResponse;

try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();

HttpEntity entity = httpResponse.getEntity();

if (entity != null) {

InputStream instream = entity.getContent();
response = convertStreamToString(instream);

// Closing the input stream will trigger connection release
instream.close();
}
SERVICE_URL+=SERVICE_URL;
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}

return response;
}

private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}}

现在在 AsyncTask 中你可以调用你的 Web 服务,可以是 Post、Get 等。你还可以轻松添加 Header

示例:

@Override
protected Void doInBackground(Void... voids) {

try {

RestClient client = new RestClient("your url goes here");
client.AddParam("param1", "value1"));
client.AddParam("param2", "value2"));
client.AddHeader("Headername","Value");
client.Execute(RequestMethod.POST);
response = client.getResponse();

}catch (Exception e) {
e.printStackTrace();
}
return null;
}

对于 GET 方法,只需将“client.Execute(RequestMethod.POST)”替换为“client.Execute(RequestMethod.GET)”

关于java - Android 开发中如何在没有 BasicNameValuePair 的情况下将数据发送到 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37782782/

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