Weibo 개발 1 클라이언트 http 패키징 가져오기 및 게시

WBOY
풀어 주다: 2016-08-08 09:31:59
원래의
846명이 탐색했습니다.

이 블로그에서는 클라이언트가 Http 프로토콜을 캡슐화하는 방법과 클라이언트가 가장 핵심 코드 중 하나인 post 및 get 메소드를 사용하는 방법에 대해 설명합니다.

다음은 Huang Shijun의 "Android and PHP 개발"

패키지 com.app.demos.util;


import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap ;
java.util.Iterator 가져오기;
java.util.List 가져오기;
java.util.Map 가져오기;
org.apache.http.HttpEntity 가져오기;
org.apache 가져오기 .http.HttpHost;
org.apache.http.HttpResponse 가져오기;
org.apache.http.HttpStatus 가져오기;
org.apache.http.NameValuePair 가져오기;
org.apache.http 가져오기 .client.HttpClient;
org.apache.http.client.entity.UrlEncodedFormEntity 가져오기;
org.apache.http.client.methods.HttpGet 가져오기;
org.apache.http.client.methods 가져오기 .HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
org.apache.http.message.BasicNameValuePair 가져오기;
org.apache.http.params.BasicHttpParams 가져오기;
org.apache.http.params.HttpConnectionParams 가져오기;
org.apache.http 가져오기 .params.HttpParams;
org.apache.http.protocol.HTTP 가져오기;
org.apache.http.util.EntityUtils 가져오기;
com.app.demos.base.C 가져오기;
import android.util.Log;
@SuppressWarnings("rawtypes")
public class AppClient {

// 압축 전략
final private static int CS_NONE = 0;
final private static int CS_GZIP = 1;

// 논리 변수
private String apiUrl;
private HttpParams httpParams;
private HttpClient httpClient;
private int timeoutConnection = 10000;
private int timeoutSocket = 10000;
private int 압축 = CS_NONE;

// charset 기본 utf8
private String charset = HTTP.UTF_8;

public AppClient(문자열 url) {
initClient(url);
}

공용 AppClient(문자열 URL, 문자열 charset, int 압축) {
initClient(url);
this.charset = charset; // charset 설정
this. 압축 = 압축 ; // 전략 설정
}

private void initClient (String url) {
// API URL 초기화

this.apiUrl = C.api.base + url;                                                                       수업 내

            package com.app.demos.base;
           공개 최종 클래스 C {

   ////// ///////////////////////////////////////////////// /////////////////////////////////////
   / / 핵심 설정(중요)

   public static final class dir {
public static final String base = "/sdcard/demos";
public static final String faces= base + "/faces";
public static final String Images = 기본 + "/이미지";
}

공개 정적 최종 클래스 API {
public static final String base= "http://192.168.1.2:8001";
public static final String index= "/index/index";
public static final String login= "/index/login";
public static final String 로그아웃= "/index/logout";
public static final String FaceView = "/image/faceView";
public static final String FaceList = "/image/faceList";
public static final String blogList= "/blog/blogList";
public static final String blogView= "/blog/blogView";
public static final String blogCreate= "/ blog/blogCreate";
public static final String commentList= "/comment/commentList";
public static final String commentCreate = "/comment/commentCreate";
public static final String customerView= "/customer/customerView";
public static final String customerEdit= "/customer/customerEdit";
public static final String fanAdd= "/customer/fansAdd";
public static final String fanDel= "/customer/fansDel";
public static final String 통지= "/notify/notice" ;
}

public static final class task {
public static final int index= 1001;
공개 정적 최종 int 로그인= 1002;
공개 정적 최종 int 로그아웃= 1003;
public static final int FaceView= 1004;
public static final int FaceList= 1005;
public static final int blogList= 1006;
public static final int blogView= 1007;
public static final int blogCreate= 1008;
public static final int commentList= 1009;
public static final int commentCreate= 1010;
public static final int customerView= 1011;
public static final int customerEdit= 1012;
public static final int fanAdd= 1013;
public static final int fanDel= 1014;
공개 정적 최종 int 공지= 1015;
}

public static final class err {
public static final String network= "网络错误";
public static final String message= "消息错误";
public static final String jsonFormat= "消息格式错误";
}

//////////////////////////// ///////////////////////////////////////////////// ////////////////
// 인텐트 및 액션 설정

public static final 클래스 인텐트 {
public static final 클래스 액션 {
public static final String EDITTEXT= "com.app.demos.EDITTEXT ";
public static final String EDITBLOG= "com.app.demos.EDITBLOG";
}
}

public static final class action {
public static final class edittext {
public static final int CONFIG= 2001;
public static final int COMMENT= 2002;
}
}

////////////////////////////// /////////////////////////////////////////////// ////// /////////////
// 추가 설정

public static final class web {
public static final String base= "http://192.168.1.2:8002";
public static final String index= base + "/index.php";
public static final String gomap= base + "/gomap.php";
}
}

String apiSid = AppUtil.getSessionId(); //AppUtil은 나중에 소개될 사용자 세션 획득, 암호화, gzip 압축 등과 같은 몇 가지 기본 사용법을 캡슐화하는 자체 작성 도구 클래스입니다.
if (apiSid != null && apiSid.length() > 0) {
this.apiUrl += "?sid=" + apiSid;
}
// 클라이언트 시간 제한 설정
httpParams = new BasicHttpParams();
HttpConnectionParams. setConnectionTimeout(httpParams, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);
// 클라이언트 초기화

httpClient = new DefaultHttpClient(httpParams);

// 간단히 httpclient를 얻는 방법입니다.

}

공개 무효 userwap ( ) {                                         //인터넷에 접속하기 위해 wap을 선택하는 방법은 다음과 같습니다
HttpHost Proxy = new HttpHost("10.0.0.172", 80, "http");
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, 프록시);
}

공개 문자열 get( )에서 예외 발생 { //Encapsulate Http get 메서드
try {
HttpGet httpGet = headerFilter(new HttpGet(this.apiUrl) )) ;
Log.w("AppClient.get.url", this.apiUrl);
// 요청 보내기
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String httpResult = resultFilter (httpResponse.getEntity());
Log.w("AppClient.get.result", httpResult);
return httpResult;
} else {
return null;
}
} catch(ConnectTimeoutException e) {
throw new Exception(C.err.network);
} catch(Exception e) {
e.printStackTrace();
}
return null;
}

공개 문자열 게시물 (HashMap urlParams) 예외 발생 {//Http 게시 방법 캡슐화
try {
HttpPost httpPost = headerFilter(new HttpPost(this.apiUrl) ) );
List postParams = new ArrayList();
// 게시 매개변수 가져오기
Iterator it = urlParams.entrySet().iterator();
while (it.hasNext()) {
Map.Entry 항목 = (Map.Entry) it .next();
postParams.add(new BasicNameValuePair(entry.getKey().toString(), Entry.getValue().toString()));
}
// 데이터 문자 집합 설정
if (this.charset != null) {
httpPost.setEntity(new UrlEncodedFormEntity (postParams, this.charset));
} else {
httpPost.setEntity(new UrlEncodedFormEntity(postParams));
}
Log.w("AppClient.post.url", this.apiUrl);
Log.w("AppClient.post.data", postParams . toString());
// 게시물 요청 보내기
HttpResponse httpResponse = httpClient.execute(httpPost);
if ( httpResponse .getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String httpResult = resultFilter(httpResponse.getEntity());
Log.w( " AppClient.post.result", httpResult);
return httpResult;
} else {
return null;
}
} catch(ConnectTimeoutException e) {
throw new Exception(C.err.network);
} catch(예외 e) {
e.printStackTrace();
}
return null;
}

비공개 HttpGet 헤더 필터(HttpGet httpGet) { 가져오기 데이터 전송 요청을 처리하여 압축 형식인지 확인
switch(this.compress) {
case CS_GZIP:
httpGet.addHeader("Accept-Encoding", "gzip");
break;
default :
중단;
}
return httpGet;
}

private HttpPost headerFilter(HttpPost httpPost) { 포스트 데이터 전송 요청을 처리하여 압축 형식인지 확인
스위치(this.compress) {
case CS_GZIP:
httpPost.addHeader("Accept-Encoding", "gzip");
break;
기본값:
break;
}
return httpPost;
}

private String resultFilter(HttpEntity 엔터티){ 얻은 데이터가 압축 형식인지 확인하기 위해 처리
문자열 결과 = null
시도 {
스위치(this.compress) {
case CS_GZIP:
결과 = AppUtil.gzipToString(entity);
break;
기본값:
결과 = EntityUtils.toString(entity);
break;
}
} catch(IOException e) {
e.printStackTrace();
}
결과 반환;
}

}

위 내용은 관련 내용을 포함하여 Weibo Development 1 클라이언트의 HTTP get 및 post 패키지를 소개합니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!