您好,我是Android编程的新手。我想制作可以将Android连接到Web服务器的应用程序。这是我使用的代码:
public void cari (View v){
ArrayList<NameValuePair> arData = new ArrayList<NameValuePair>();
arData.add(new BasicNameValuePair("nama", edNama.getText().toString()));
String respon = null;
try {
respon = KoneksiHTTP.eksekusiHttpPost("http://example.com/myphp.php", arData);
String r = respon.toString();
r = r.trim();
AlertDialog close = new AlertDialog.Builder(this)
.setTitle("ESTIMASI MANFAAT")
.setMessage(r.toString())
.setNegativeButton("Kembali", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int sumthin) {
// TODO Auto-generated method stub
}
})
.show();
} catch (Exception e) {
e.printStackTrace();
}
finally {
edNama.setText(null);
}
}
和另一个班级
public class KoneksiHTTP {
public static final int HTTP_TIMEOUT = 3000;
private static HttpClient client;
private static HttpClient getHttpClient() {
if (client == null) {
client = new DefaultHttpClient();
final HttpParams parameterHttp = client.getParams();
HttpConnectionParams.setConnectionTimeout(parameterHttp, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(parameterHttp, HTTP_TIMEOUT);
}
return client;
}
public static String eksekusiHttpPost(String url, ArrayList<NameValuePair> postParameter) throws Exception {
BufferedReader in = null;
try {
HttpClient klien = getHttpClient();
HttpPost req = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameter);
req.setEntity(formEntity);
HttpResponse resp = klien.execute(req);
in = new BufferedReader(new InputStreamReader(resp.getEntity()
.getContent()));
StringBuffer stringBuff = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
stringBuff.append(line + NL);
}
in.close();
String hasil = stringBuff.toString();
return hasil;
} finally {
if (in != null) {
in.close();
}
}
}
}
但我
上的已弃用HttpParams,HttpConnectionParams,ConnManagerParams,setTimeout。
我一直在添加
useLibrary 'org.apache.http.legacy'
但没有效果。我应该用什么呢?
这是我的构建gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.example.plz.taspenmobile"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.google.android.gms:play-services-maps:8.4.0'
compile 'com.google.android.gms:play-services-location:8.4.0'
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
compile 'org.apache.httpcomponents:httpclient:4.5'
}
显示回复的代码:
try {
CallWebService respon = new CallWebService("POST", "http://example.com/myphp.php", apiParams) {
@Override
public void OnStartingService() {
super.OnStartingService();
}
//@Override
public void OnGettingResult(JSONObject jsonObject) throws JSONException, MethodNotDefinedException {
super.OnGettingResult(toString());
}
};
String r = respon.toString();
r = r.trim();
AlertDialog close = new AlertDialog.Builder(estimasi.this)
.setTitle("Estimasi Manfaat")
.setMessage(r.toString())
.setNegativeButton("Kembali", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int sumthin) {
// TODO Auto-generated method stub
}
})
.show();
} catch (Exception e) {
e.printStackTrace();
}
finally {
edNama.setText(null);
}
答案 0 :(得分:0)
您必须使用HttpURLConnection
。
使用以下2种方法作为参考。
<强> 1。对于GET方法。
public static String getHttpResponse(String url) {
StringBuffer responseString = null;
String inputLine;
HttpURLConnection connection = null;
try {
URL dataUrl = new URL(url);
connection = (HttpURLConnection) dataUrl.openConnection();
// optional default is GET
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
responseString = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseString.append(inputLine);
}
in.close();
}
} catch (Exception e) {
Log.w("Some error occured", e);
return null;
} finally {
try {
connection.disconnect();
} catch (Exception e) {
e.printStackTrace(); //If you want further info on failure...
return null;
}
}
return responseString.toString();
}
<强> 2。对于POST方法。
public static String postHttpResponse(String dataUrl, HashMap<String, String> postData) {
StringBuffer responseString = null;
HttpURLConnection connection = null;
String inputLine;
try {
URL postUrl = new URL(dataUrl);
String email_id = postData.get("email_id");
String device_id = postData.get("device_id");
String status = postData.get("status");
connection = (HttpURLConnection) postUrl.openConnection();
String urlParameters = "device_id=" + device_id + "&email_id=" + email_id + "&status=" + status;
connection.setRequestMethod("POST");
connection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = connection.getResponseCode();
if (responseCode == 200) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
responseString = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
responseString.append(inputLine);
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
connection.disconnect();
} catch (Exception e) {
e.printStackTrace(); //If you want further info on failure...
return null;
}
}
return responseString.toString();
}
答案 1 :(得分:0)
你好我认为你应该切换到httpURlConnection。只需访问this 在这里链接我添加了用于调用webservice的全局类并在json中获取响应。
在CallWebService文件中替换此代码,您将获得字符串响应。
public class CallWebService {
private static final String GET="GET";
private static final String POST="POST";
private HashMap<String,String> apiParameters;
private static String WebService;
public CallWebService(String MethodType, String WebService, HashMap<String, String> apiParameters) throws MethodNotDefinedException {
if(MethodType!=null) {
if (MethodType.equalsIgnoreCase(GET)) {
if(WebService!=null){
this.WebService=WebService;
new ExecuteAsyncTask(GET).execute();
}else{
throw new NullPointerException("Please define webservice url.");
}
} else if(MethodType.equalsIgnoreCase(POST)){
if(WebService!=null){
if(apiParameters!=null)this.apiParameters=apiParameters;
this.WebService=WebService;
new ExecuteAsyncTask(POST).execute(apiParameters);
}else{
throw new NullPointerException("Please define webservice url.");
}
}else{
throw new MethodNotDefinedException("Define method for webservice.");
}
}else{
throw new MethodNotDefinedException("Define method for webservice.");
}
}
private class ExecuteAsyncTask extends AsyncTask<HashMap<String,String>,Void,String>{
String MethodType;
public ExecuteAsyncTask(String MethodType){
this.MethodType=MethodType;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
OnStartingService();
}
@Override
protected void onPostExecute(String string) {
super.onPostExecute(string);
try {
OnGettingResult(string);
} catch (JSONException e) {
e.printStackTrace();
} catch (MethodNotDefinedException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(HashMap<String, String>... params) {
if(MethodType.equalsIgnoreCase(GET))
return getJSON(WebService,15000);
else try {
return getJSONPOST(WebService,params[0]);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
public void OnStartingService(){
}
public void OnGettingResult(String jsonObject) throws JSONException, MethodNotDefinedException {
}
private String getJSON(String url, int timeout) {
HttpURLConnection c = null;
try {
URL u = new URL(url);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
System.out.println(sb.toString());
return sb.toString();
}
} catch (MalformedURLException ex) {
} catch (IOException ex) {
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
}
}
}
return null;
}
private String getJSONPOST(String url1, HashMap<String,String> apiParams) throws IOException, JSONException {
URL url = new URL(url1);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String getParams=getQuery(apiParams);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getParams);
writer.flush();
writer.close();
os.close();
conn.connect();
int status = conn.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
System.out.println(sb.toString());
return sb.toString();
}
if (conn != null) {
try {
conn.disconnect();
} catch (Exception ex) {
}
}
return null;
}
private String getQuery(HashMap<String,String> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
答案 2 :(得分:0)
我的其他建议是使用Android Volley
。您可以在此处查看信息和用法:Training With Volley
答案 3 :(得分:0)
将此@SuppressWarnings注释放在使用HttpClient的类定义上:
myProject.go
但您的应用仍然可以在Android的未来版本中中断,因此无论如何都要迁移您的代码。
答案 4 :(得分:0)
String r = apiParams.toString();
r = r.trim();
AlertDialog close = new AlertDialog.Builder(estimasi.this)
.setTitle("Estimasi Manfaat")
.setMessage(r.toString())
.setNegativeButton("Kembali", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlg, int sumthin) {
// TODO Auto-generated method stub
}
})
.show();