با سلام ... کد ها دیپرکیت شده کارمیکنن اگر در نسخه های پایین تر کامپایل شن ولی شما میتونید از HttpURLConnection هم استفاده کنید .... راه حل زیاد داره نگران نباشید
بروز خطا
[message]
اشتراک در سوال
رای ها
[dataList]
پرسش و پاسخ
الان دیگه مطمءن شدم آموزش های قبلی در بعضی موارد به درد نمیخورن
مدیریت گفتگو
آخرین تغییر: 10 سال پیش
بخش 11 هستم.طبق کارای استاد پیش رفتم.اما نتیجه ای که تو فیلم استاد بودن بهم نشون نمیداد.یعنی اصلا کار نمیکرد.باری اطمینان برنامه ای که خود استاد نوشتن هم تست کردم.همین بود.سرج کردم رسیدم به انجمن خودمون که فهمیدم HTTPCLIENT منسوخ شده. الان چاره من چیه؟چطوری بخش ارتباط به سرور و وب رو ادامه بدم؟
پاسخها 4
دوستان طریقه استفاده از HTTPclient چطوریه؟
الان این کد استاد هستش.فقط اسم فرق میکنه.چی رو باید حایگزین کنم!!
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.43.131/mysite/");
Log.i("ONE", "1 is starting");
try {
HttpResponse httpResponse = client.execute(httpPost);
int code = httpResponse.getStatusLine().getStatusCode();
Toast.makeText(getApplicationContext(), "Internet Code is " + code, Toast.LENGTH_SHORT).show();
InputStream stream = httpResponse.getEntity().getContent();
Log.i("Key", inputStreamToString(stream) + "");
}
catch (ClientProtocolException e) {}
catch (IOException e) {}
}
public String inputStreamToString(InputStream stream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
return "";
}
نظرات
سلام متاسفانه خیلی کلاسا مثل همین کلاس در api23 کلا depricate شده که استاد بازم اسرار داره از همین کلاس ها استفاده کنیم که جای سوال داره واقعا اما هنوزم میشه با روش هایی از این کلاسا استفاده کرد که توصیه نمیشه اصلا.
public class HttpRequest {
//Supported HttpRequest methods
public static enum Method{
POST,PUT,DELETE,GET;
}
private URL url;
private HttpURLConnection con;
private OutputStream outputStream;
//After instantiation, when opening connection - IOException can occur
public HttpRequest(URL url)throws IOException{
this.url=url;
con = (HttpURLConnection)this.url.openConnection();
}
//Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
public HttpRequest(String url)throws IOException{ this(new URL(url)); }
/**
* Sending connection and opening an output stream to server by pre-defined instance variable url
*
* @param isPost boolean - indicates whether this request should be sent in POST method
* @throws IOException - should be checked by caller
* */
private void prepareAll(Method method)throws IOException{
con.setDoInput(true);
con.setRequestMethod(method.name());
if(method== Method.POST||method== Method.PUT){
con.setDoOutput(true);
outputStream = con.getOutputStream();
}
}
//prepare request in GET method
//@return HttpRequest this instance -> for chaining method @see line 22
public HttpRequest prepare() throws IOException{
prepareAll(Method.GET);
return this;
}
/**
* Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
* HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
*
* @param method HttpRequest.Method - nested enum HttpRequest.Method constant
* @return HttpRequest this instance -> for chaining method @see line 22
* @throws IOException - should be checked by caller
* */
public HttpRequest prepare(Method method)throws IOException{
prepareAll(method);
return this;
}
/**
* Adding request headers (standard format "Key":"Value")
*
* @param headers String variadic params in standard format "Key":"Value"
* @return HttpRequest this instance -> for chaining method @see line 22
* */
public HttpRequest withHeaders(String... headers){
for(int i=0,last=headers.length;i<last;i++) {
String[]h=headers[i].split("[:]");
con.setRequestProperty(h[0],h[1]);
}
return this;
}
/**
* Writes query to open stream to server
*
* @param query String params in format of key1=v1&key2=v2 to open stream to server
* @return HttpRequest this instance -> for chaining method @see line 22
* @throws IOException - should be checked by caller
* */
public HttpRequest withData(String query) throws IOException{
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
return this;
}
/**
* Builds query on format of key1=v1&key2=v2 from given hashMap structure
* for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
* for map: {Iam=Groot} -> builds "Iam=Groot"
*
* @param params HashMap consists of key-> value pairs to build query from
* @return HttpRequest this instance -> for chaining method @see line 22
* @throws IOException - should be checked by caller
* */
public HttpRequest withData(HashMap<String,String> params) throws IOException{
StringBuilder result=new StringBuilder();
for(Map.Entry<String,String>entry : params.entrySet()){
result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
}
withData(result.toString());
return this;
}
//When caller only need to send, and don't need String response from server
public int send() throws IOException{
return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
}
/**
* Sending request to the server and pass to caller String as it received in response from server
*
* @return String printed from server's response
* @throws IOException - should be checked by caller
* */
public String sendAndReadString() throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder response=new StringBuilder();
for(String line;(line=br.readLine())!=null;)response.append(line+"\n");
return response.toString();
}
/**
* Sending request to the server and pass to caller its raw contents in bytes as it received from server.
*
* @return byte[] from server's response
* @throws IOException - should be checked by caller
* */
public byte[] sendAndReadBytes() throws IOException{
byte[] buffer = new byte[8192];
InputStream is = con.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead);
return output.toByteArray();
}
//JSONObject representation of String response from server
public JSONObject sendAndReadJSON() throws JSONException, IOException{
return new JSONObject(sendAndReadString());
}
}
نظرات
و حالا برای استفاده از کلاس بالا به این روش ها میتونی بری جلو
HttpRequest req=new HttpRequest("http://host:port/path");
exmple1:
req.prepare(HttpRequest.Method.POST).withData("name=Bubu&age=29").send();
//***************************************************************
example2:
HashMap<String, String> params=new HashMap<>(); params.put("name", "Groot"); params.put("age", "29"); req.prepare(HttpRequest.Method.POST).withData(params).sendAndReadJSON();
نظرات
پاسخگویی و مشاهده پاسخ های این سوال تنها برای اعضای ویژه سایت امکان پذیر است .
چنانچه تمایل دارید به همه بخش ها دسترسی داشته باشید میتوانید از این بخش لایسنس این آموزش را خریداری نمایید .
ویرایش
پیام
نظرات